﻿using System;
using System.Data;
using Microsoft.SharePoint;

namespace SKN
{
    /// <summary>
    /// 
    /// </summary>
    public static class ChangeLog
    {
        /// <summary>
        /// Use this method to get all the items from the change log
        /// </summary>
        /// <param name="web"></param>
        public static DataTable GetItems(SPWeb web)
        {
            var dtChanges = new DataTable();
            dtChanges.Columns.Add("List");
            dtChanges.Columns.Add("Item");
            dtChanges.Columns.Add("Time");
            dtChanges.Columns.Add("Change Type");

            SPListCollection collLists = web.Lists;

            SPRegionalSettings oRegionSettings = web.RegionalSettings;
            SPTimeZone oTimeZone = oRegionSettings.TimeZone;

            var oQuery = new SPChangeQuery(true, true);
            SPChangeCollection collChanges = web.GetChanges(oQuery);
            
            
            foreach (SPChange oChange in collChanges)
            {
                switch (oChange.GetType().ToString())
                {
                    case "Microsoft.SharePoint.SPChangeItem":
                        var oChangedItem = (SPChangeItem) oChange;
                        try
                        {
                            DataRow dr = dtChanges.NewRow();
                            dr["List"] = collLists[oChangedItem.ListId].Title;
                            dr["Item"] = collLists[oChangedItem.ListId].GetItemByUniqueId(oChangedItem.UniqueId).Name;
                            dr["Time"] = oTimeZone.UTCToLocalTime(oChangedItem.Time);
                            dr["Change Type"] = oChangedItem.ChangeType;
                            dtChanges.Rows.Add(dr);
                        }
                        catch
                        {
                            throw new Exception("The object to which item " + oChangedItem.UniqueId +
                                                " belongs does not exist.<BR>");
                        }
                        break;
                }
            }

            dtChanges.AcceptChanges();

            return dtChanges;
        }
    }
}